home *** CD-ROM | disk | FTP | other *** search
/ Software Vault: The Gold Collection / Software Vault - The Gold Collection (American Databankers) (1993).ISO / cdr26 / netprog.zip / NETPROG.TAR / lock / locksem1.c < prev    next >
C/C++ Source or Header  |  1989-12-17  |  869b  |  43 lines

  1. /*
  2.  * Locking routines using semaphores.
  3.  * Use the SEM_UNDO feature to have the kernel adjust the
  4.  * semaphore value on premature exit.
  5.  */
  6.  
  7. #include    <sys/types.h>
  8. #include    <sys/ipc.h>
  9. #include    <sys/sem.h>
  10.  
  11. #define    SEMKEY    123456L    /* key value for semget() */
  12. #define    PERMS    0666
  13.  
  14. static struct sembuf    op_lock[2] = {
  15.     0, 0, 0,    /* wait for sem#0 to become 0 */
  16.     0, 1, SEM_UNDO    /* then increment sem#0 by 1 */
  17. };
  18.  
  19. static struct sembuf    op_unlock[1] = {
  20.     0, -1, (IPC_NOWAIT | SEM_UNDO)
  21.             /* decrement sem#0 by 1 (sets it to 0) */
  22. };
  23.  
  24. int    semid = -1;    /* semaphore id */
  25.  
  26. my_lock(fd)
  27. int    fd;
  28. {
  29.     if (semid < 0) {
  30.         if ( (semid = semget(SEMKEY, 1, IPC_CREAT | PERMS)) < 0)
  31.             err_sys("semget error");
  32.     }
  33.     if (semop(semid, &op_lock[0], 2) < 0)
  34.         err_sys("semop lock error");
  35. }
  36.  
  37. my_unlock(fd)
  38. int    fd;
  39. {
  40.     if (semop(semid, &op_unlock[0], 1) < 0)
  41.         err_sys("semop unlock error");
  42. }
  43.